/**
 * @class   wosh::automations::Automation
 * @brief   Interface for home automations, holds properties and basic methods.
 *          Messages are evaluated by isTrigger() function, when the call
 *          returns true, the manager will run execute().
 *
 * @see     wosh::interfaces::services::TaskManager
 ****************************************************************************
 * @version 0.8.013 $Id: Automation.h 2867 2010-08-07 20:44:51Z alex $
 * @author  Alessandro Polo
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

#ifndef __WOSH_Automations_Automation_H__
 #define __WOSH_Automations_Automation_H__

 #include <woshDefs.h>
 #include <core/Object.h>
 #include <core/Fact.h>
 #include <core/Containers.h>
 #include <core/BusConnector.h>
 #include <core/MessageFilter.h>
 #include <core/PropertiesProvider.h>
 #include <core/MethodsProvider.h>
 #include <core/LogContext.h>


namespace wosh {
 template <class T> class DataFieldCollector;
 namespace automations {

 #define _Automation_KEY_id					"ID"
 #define _Automation_KEY_enabled			"Enabled"
 #define _Automation_KEY_description		"Description"
 #define _Automation_KEY_priority			"Priority"

 #define _Automation_KEY_MonitoredBusses	"MonitoredBusses"

 #define _Automation_KEY_ModeMapping		"ModeMapping"

 #define _Automation_KEY_LastTrigger		"LastTrigger"
 #define _Automation_KEY_LastExecutedTime	"LastExecutedTime"

 #define _Automation_METHOD_execute			"execute"

 #define _Automation_EVENT_Executed			"AutomationExecuted"


class Automation :	public Object,
					public virtual IPropertiesProviderListener,
					public virtual IBusListener,
					public MethodRunner
 {
	WOSH_SERIALIZABLE(wosh::automations::Automation)
	WOSH_COMPARE_RTTI(wosh::automations::Automation)


	typedef MapT<MessageFilter*, int> tMessageFilterIntMap;
	typedef ListT<Message*> tMessageList;

	public:
		/// state of the kernel
		enum MODE_EFFECT_MAPPING {
			MAPPING_UNKNOWN			= 0x00, ///< unknown mode
			MAPPING_ANY_TRIGGER		= 0x01, ///< any of the triggers will generate ALL effects
			MAPPING_INDEX_TRIGGER	= 0x02 ///< Nth trigger raises Nth effect (index based)
		 };


	public:
		/**
		 * @brief  Empty constructor.
		 */
		Automation();
		/**
		 * @brief  Copy constructor.
		 * @param m [in] the source object to be copied
		 */
		Automation( const Automation& m );
		/**
		 * @brief  Empty destructor.
		 */
		virtual ~Automation();


	public:

		virtual WRESULT init();
		virtual WRESULT deinit();

		virtual WRESULT execute( const Message* trigger_message, const MessageFilter* trigger_filter = NULL );

		virtual void evaluateMessageTrigger( const Message& message );

/** @name Message Events (incoming message)
 * @{
 ******************************************************************************/
	public:
		virtual void busMessage( const Message& message, const Bus* source );
//@}
/** @name Getters
 * @{
 ******************************************************************************/
	public:
		inline int64 getID() const								{ return this->uid; }

		inline bool isEnabled() const							{ return this->enabled; }

		inline int getPriority() const							{ return this->priority; }

		inline int64 getLastExecutedTime() const				{ return this->lastExecutedTime; }
		inline int64 getLastTrigger() const						{ return this->lastTrigger; }

		inline std::string getDescription() const				{ return this->Properties.getValueOf(_Automation_KEY_description).toString(); }

		void getMonitoredBusses( std::vector<std::string>& busses ) const;

		inline MODE_EFFECT_MAPPING getModeMapping() const		{ return this->mode_mapping; }

		inline const tMessageFilterIntMap& getTriggers() const	{ return this->triggers; }
		inline tMessageFilterIntMap& getTriggers() 				{ return this->triggers; }

		inline const tMessageList& getEffects() const			{ return this->effects; }
		inline tMessageList& getEffects() 						{ return this->effects; }

		inline const PropertiesProvider& getProperties() const	{ return this->Properties; }
		inline PropertiesProvider& getProperties() 				{ return this->Properties; }

		inline const MethodsProvider& getMethods() const		{ return this->Methods; }
		inline MethodsProvider& getMethods()					{ return this->Methods; }

		static DataFieldCollector<Automation>* getDataFields();

//@}
/** @name Setters
 * @{
 ******************************************************************************/
	public:
		void setID( int64 value );

		void setEnabled( bool value );

		virtual void setName( const std::string& basename, long id );

		void setDescription( const std::string& value );

		void setPriority( int priority );

		void setMonitoredBusses( const std::vector<std::string>& busses );

		void setModeMapping( MODE_EFFECT_MAPPING mode_mapping );

		virtual void clear();

//@}
/** @name IPropertiesProviderListener interface
 * @{
 ******************************************************************************/
 	public:
		virtual bool readingProperty( Property*, const PropertiesProvider* ) { return true; }
		virtual bool updatingProperty( bool& doUpdate, const Variant& value_proposed, Property& property_current, const PropertiesProvider* source );
//@}
/** @name Operators Overloading
 * @{
 ******************************************************************************/
	public:
		virtual Automation& operator=(const Automation& m);
		virtual bool operator==(const Automation &other) const;
//@}
/** @name Serialization interface
 * @{
 ******************************************************************************/
	public:
		virtual std::string toString() const;
		virtual bool updateHash( DataHashContext* hash_context ) const;
//@}
	protected:
		virtual void postMessage( Message* message, const SecurityToken* source_token = NULL );
		virtual SecurityToken* signMessage( Message* message, const SecurityToken* source_token = NULL ) const;

		void setLastExecutedTime( int64 time = -1 );
		void setLastTrigger( const Message* trigger_message );

		Message* generateEffect( const Message* effect_template, const Message* trigger_message, const MessageFilter* trigger_filter = NULL ) const;
		WRESULT execute_( const Message* trigger_message, const MessageFilter* trigger_filter = NULL, int trigger_index = 0 );

		void updateVariables( Message* message, const Message* trigger_message = NULL ) const;
		WRESULT replaceVariable( Message* message, const Message* trigger_message, const std::string& key, const Variant& value ) const;

	private:
		Response* mmDoExecute( const Message* messageRequest );

	protected:
		int64 uid;								///< unique ID of 
		bool enabled;							///< flag indicating if Automation is enabled
		int priority;							///< automation's priority

		BusConnector BusAutomation;				///< Automation bus connector
		mutable PropertiesProvider Properties;	///< my configuration
		mutable MethodsProvider Methods;		///< my methods
		mutable LogContext Log;					///< my logger

		tMessageFilterIntMap triggers;			///< triggers
		tMessageList effects;					///< effects
		MODE_EFFECT_MAPPING mode_mapping;		///< define how triggers and effects are mapped

	protected:
		int64 lastExecutedTime;					///< timestamp (epoch) of last execution
		int64 lastTrigger;


}; // class def






/**
 * @class   wosh::Automation_Executed
 * @brief   Raised when 
 *
 * Internally, data is stored as wosh::Variant (STRING).
 *
 * Fields are:
 *  - \c 
 *

 * \code
 * \endcode
 *
 * @see     wosh::Fact
 * @see     wosh::WoshHost
 ****************************************************************************
 * @version 0.8.399 $Id: Automation.h 2867 2010-08-07 20:44:51Z alex $
 * @author  Alessandro Polo
 ****************************************************************************/
class Automation_Executed : public wosh::Fact
 {
	WOSH_SERIALIZABLE(wosh::automations::Automation_Executed)

	public:
		/**
		 * @brief  Empty constructor.
		 */
		Automation_Executed()
			: wosh::Fact( _Automation_EVENT_Executed ) { }
		/**
		 * @brief  Constructor with initializers.
		 * @param automation [in] the subject (host) of the event
		 */
		Automation_Executed( const wosh::automations::Automation* automation, const Message* trigger );

		/**
		 * @brief  Copy constructor.
		 * @param m [in] the source object to be copied
		 */
		Automation_Executed( const Automation_Executed& m )
			: wosh::Fact(m) { }
		/**
		 * @brief  Empty destructor.
		 */
		virtual ~Automation_Executed() { }

	public:


}; // class def






 }; // namespace automations
}; // namespace wosh

#endif //__WOSH_Automations_Automation_H__
